package com.ymatou.iapi.trading.sellerquery2.parameter;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.StockStatusEnum;
import com.ymatou.iapi.trading.ordersync.service.BigDecimalUtil;
import com.ymatou.iapi.trading.sellerquery2.parameter.resp.OrderInfo;
import com.ymatou.iapi.trading.sellerquery2.parameter.resp.OrderItemInfo;
import com.ymatou.iapi.trading.sellerquery2.parameter.resp.OrderItemInfoExt;
import com.ymatou.tool.FormatUtil;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.common.order.userquery.OrderInfoBuilder;
import com.ymttest.common.order.userquery.util.OrderHelper;
import com.ymttest.common.order.userquery.util.Utils;
import com.ymttest.database.model.mongo.query.Delivery;
import com.ymttest.database.model.mongo.query.Fund;
import com.ymttest.database.model.mongo.query.Order;
import com.ymttest.database.model.mongo.query.Product;
import com.ymttest.database.model.mongo.query.Refund;

public class OrderRepository {

	/**
	 * 调用接口查询mongo 数据 order 数据
	 * 
	 * @param orderId
	 * */
	public static Order getOrderFromMongo(long orderId) {

		YmatouEasyCall OrderFromMongoCall = new YmatouEasyCall("", "POST",
				"JSON");
		Order order = new Order();
		String orderJson = "{\"orderId\":" + orderId + "}";
		OrderFromMongoCall
				.setUrl("http://ordersync.trading.iapi.ymatou.com/api/getOrder");
		OrderFromMongoCall.setData(orderJson);
		try {
			OrderFromMongoCall.callService();
			String jsonOrder = new JSONObject(
					OrderFromMongoCall.getReturnData()).getString("order")
					.replace("Time", "Dime").replace("T", " ")
					.replace("Dime", "Time");

			order = (Order) FormatUtil.GSONToObject(jsonOrder, Order.class);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();

			Logger.info(e);
		}

		return order;
	}
	public static OrderInfo convertOrder(Order order) {

		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setOrderId(order.getId());
		orderInfo.setUserId(order.getUserId());
		orderInfo.setBuyerId(order.getSellerId());
		orderInfo.setAddTime(order.getAddTime());
		orderInfo.setAcceptTime(order.getAcceptTime());
		orderInfo.setTradingStatus(order.getTradingStatus());
		orderInfo
				.setRiskVerifiedStatus(Utils.zeroIfNull(order.getRiskStatus()));
		orderInfo.setPaidInFull(true); //没有补款，默认值true
		orderInfo.setShangouOrder(!BigDecimalUtil.isEqual(
				order.getOrderPrice(), order.getTotalPrice()));
		orderInfo.setBuyerLoginId(order.getUserLogin());
		orderInfo.setSellerLoginId(order.getSellerLogin());
		orderInfo.setBuyerNickName(order.getUserLogin());
		orderInfo.setDispathTime(order.getDeliveryTime());
		orderInfo.setShippedByXlobo(order.isXlobo());
		orderInfo.setSalesRefundStatus(OrderHelper.getSalesRefundStatus(order
				.getRefunds()));
		orderInfo.setCancelReason(order.getReason());
		orderInfo.setMainOrderId(order.getMainOrderId());
		orderInfo.setYmtCouponAmount(order.getYmtCouponAmount());
		orderInfo.setYmtCouponCode(order.getYmtCouponCode());
		orderInfo.setSellerCouponAmount(Utils.zeroIfNull(order
				.getSellerCouponAmount()));
		orderInfo.setSellerCouponCode(order.getSellerCouponCode());
		orderInfo.setPayableAmount(order.getPayableAmount());
		orderInfo.setRealSettlementAmountOfCoupon(order.getFund()
				.getRefundCoupon());
		if (null != order.getDelivery()) {
			orderInfo.setBusynessTypeList(order.getDelivery().getBizType());
		}
		orderInfo.setOrderPrice(order.getOrderPrice());
		orderInfo.setOrderDiscount(order.getPreDiscount());
		orderInfo.setFreight(order.getFreight());
		orderInfo.setDiscount(order.getPostDiscount());
		orderInfo.setTotalPrice(order.getTotalPrice());
		orderInfo.setNeedPrePayAmountOfCash(OrderHelper
				.getNeedPrePayAmountOfCash(order));
		orderInfo.setTotalSalesRefundAmount(order.getRefunds().stream()
				.filter(e -> e.getRefundStatus().equals(10))
				.map(e -> Utils.zeroIfNull(e.getRefundAmount()))
				.reduce(BigDecimal::add).orElse(BigDecimal.ZERO));

		orderInfo.setAddress(order.getAddress());
		orderInfo.setPostCode(order.getPostCode());
		orderInfo.setReceivePerson(order.getReceiver());
		orderInfo.setPhone(order.getPhone());
		orderInfo.setTelephone(order.getTelephone());
		orderInfo.setEmail(order.getEmail());
		orderInfo.setLeaveWord(order.getComment());
		orderInfo.setCouponCode(order.getYmtCouponCode());
		orderInfo.setCouponValue(order.getYmtCouponAmount() != null ? order
				.getYmtCouponAmount() : BigDecimal.ZERO);
		orderInfo.setSellerCouponCode(order.getSellerCouponCode());
		orderInfo.setSellerCouponAmount(order.getSellerCouponAmount() != null
				? order.getSellerCouponAmount()
				: BigDecimal.ZERO);
		orderInfo.setPaidTime(order.getPaidTime());
		orderInfo.setApplyPostPayTime(order.getApplyPostTime());
		orderInfo.setPostPaidTime(order.getPostTime());
		orderInfo.setConfirmedTime(order.getReceiveTime());
		orderInfo.setCancelTime(order.getCancelTime());
		orderInfo.setDispatchTime(order.getDeliveryTime());
		orderInfo.setAutoCancelOrderHours(order.getAutoCancelHour());
		orderInfo.setPreSaleOrder(order.isPreSale());
		orderInfo.setTradingId(order.getTradingId() != null
				&& order.getTradingId() > 0 ? order.getTradingId() : order
				.getMainOrderId());
		orderInfo.setPromotionReducedAmount(order.getSellerPromotionAmount());

		//YMT_OrderInfo => Order.Product
		List<Product> products = order.getProducts();
		boolean isExistProductInfo = !CollectionUtils.isEmpty(products);
		int logisticsType = isExistProductInfo ? Utils.zeroIfNull(products.get(
				0).getDeliveryType()) : LogisticsTypeEnum.Unknown.getCode();
		int stockStatus = isExistProductInfo ? Utils.zeroIfNull(products.get(0)
				.getStockStatus()) : StockStatusEnum.Spot.getCode();
		if (logisticsType == LogisticsTypeEnum.PackageDelivery.getCode()) {
			orderInfo.setPackageDelivery_DomesticDelivered(order
					.isLocalDelivery());
		}
		orderInfo.setLogisticsType(logisticsType);
		orderInfo.setStockStatus(stockStatus);
		orderInfo.setOrderItemList(convertProduct(products, order.getRefunds(),
				order)); //商品信息

		//YMT_OrderExt => Order
		orderInfo.setPlatformEnum(OrderHelper.getPlatformEnumInfo(
				order.getPlatSource()).getValue());
		orderInfo.setNeedUploadIdCard(order.isNeedUploadIdCard());
		orderInfo.setHaveUploadedIdCard(order.isUploadedIdCard());
		orderInfo.setNewSellerOrder(order.isNewSeller());
		orderInfo.setNewCustomerOrder(order.isNewUser());
		orderInfo.setFirstOrder(order.isFirst());

		//Ymt_O_OrderNote => Order
		orderInfo.setSellerNote(StringUtils.defaultString(order.getContent()));
		orderInfo.setRemarkLevel(order.getRemarkLevel());

		//Ymt_OrderState => Order.Fund; Ymt_RefundBill => Order.Refunds
		convertFund(orderInfo, order);

		//Ymt_Order_Frozen => Order.Delivery
		Delivery delivery = order.getDelivery();
		orderInfo.setDelayReceiveFrozenTime(delivery != null ? delivery
				.getFrozenTime() : null);
		orderInfo.setDelayReceiveUpdateTime(delivery != null ? delivery
				.getUpdateTime() : null);
		orderInfo.setDelayReceiveUserId(delivery != null
				&& delivery.getDelayUserId() != null ? delivery
				.getDelayUserId() : order.getSellerId());
		Date autoReceiveTime = delivery != null && !delivery.isPause()
				&& delivery.getFrozenTime() != null
				? delivery.getFrozenTime()
				: null;
		orderInfo.setAutoReceiveEnabled(autoReceiveTime != null);
		orderInfo.setAutoReceiveTime(autoReceiveTime);

		orderInfo.setCredited(false);
		orderInfo.setTotalPriceChange(Utils.zeroIfNull(order.getPreDiscount())
				.add(Utils.zeroIfNull(order.getPostDiscount())));

		//OrderSummary 不需要
		orderInfo.setBillCodeList(delivery != null
				? delivery.getBillCode()
				: null);

		return orderInfo;
	}

	public static OrderInfo convertFund(OrderInfo orderInfo, Order order) {
		Fund fund = order.getFund();
		orderInfo.setPostPaidAmountOfCoupon(BigDecimal.ZERO);
		orderInfo.setPostPaidAmountOfGift(fund.getPostGif());
		orderInfo.setPaidAmountOfFreeCard(fund.getPaidFreeCard());
		orderInfo.setPaidAmountOfCoupon(BigDecimal.ZERO); //废弃字段
		orderInfo.setPaidAmountOfYmtCoupon(fund.getYmtCoupon());

		orderInfo.setFirstPay(OrderHelper.getPrePaidAmount(order));
		orderInfo.setRefund(OrderHelper.getRefundedAmount(fund));
		orderInfo.setRealPay(OrderHelper.getTotalPayAmount(order).subtract(
				orderInfo.getRefund()));
		orderInfo.setRealPostPay(OrderHelper.getPostPaidAmount(fund));
		orderInfo.setPaidAmountOfCash(Utils.zeroIfNull(fund.getPaidCash()));
		orderInfo.setRealPaidAmountOfCash(OrderHelper
				.getCashAmountOfRealPay(fund));
		orderInfo.setRealPaidAmountOfGift(OrderHelper
				.getGiftAmountOfRealPay(fund));
		orderInfo
				.setDiscountOfThirdParty(Utils.zeroIfNull(fund.getDiscount3P()));
		orderInfo.setTotalRefundThirdPartyDiscount(Utils.zeroIfNull(fund
				.getRefundDiscount3P()));

		return orderInfo;
	}

	public static List<OrderItemInfo> convertProduct(List<Product> products,
			List<Refund> refunds, Order order) {
		List<OrderItemInfo> orderItemInfos = new ArrayList<>();
		for (Product product : products) {
			OrderItemInfo itemInfo = new OrderItemInfo();
			OrderItemInfoExt itemInfoExt = null;
			if (product.getActId() != null && product.getActId() > 0) {
				itemInfoExt = new OrderItemInfoExt();
				itemInfoExt.setActivityId(Utils.zeroIfNull(product.getActId()));
				itemInfoExt.setActivityTemplateId(Utils.zeroIfNull(product
						.getActTemplateId()));
			}
			itemInfo.setOrderItemInfoExt(itemInfoExt);

			itemInfo.setSailProtected(Utils.zeroIfNull(product
					.getDeliveryType()) == 3);
			itemInfo.setPrice(product.getPrdPrePrice());
			itemInfo.setPropertyInfo(product.getPropertyInfo());
			itemInfo.setAmount(Utils.zeroIfNull(product.getPrdCount()));
			itemInfo.setCatalogId(product.getCataId());
			itemInfo.setSku(product.getSku());
			itemInfo.setProductId(product.getProductId());
			itemInfo.setOrderItemId(product.getItemId());
			itemInfo.setPictureUrl(product.getPicUrl());
			itemInfo.setTitle(product.getTitle());
			itemInfo.setFirstCategoryId(product.getCata1Id());
			itemInfo.setSubProductCategoryId(product.getCata2Id());
			itemInfo.setThirdCategoryId(product.getCata3Id());
			itemInfo.setLogisticsType(Utils.zeroIfNull(product
					.getDeliveryType()));
			itemInfo.setStockStatus(Utils.zeroIfNull(product.getStockStatus()));
			itemInfo.setBondedArea(Utils.zeroIfNull(product.getBondedArea()));
			itemInfo.setPriceType(Utils.zeroIfNull(product.getPriceType()));
			itemInfo.setProductRefundChannel(Utils.zeroIfNull(product
					.getRefundChannel()));
			itemInfo.setFreight(product.getPrdFreight());
			itemInfo.setFreightFree(product.isFreightFree());
			itemInfo.setSellerCouponAmount(Utils.zeroIfNull(product
					.getPrdSellerCoupon()));
			itemInfo.setYmtCouponAmount(Utils.zeroIfNull(product
					.getPrdYmtCoupon()));
			itemInfo.setProductOriginalPrice(Utils.zeroIfNull(product
					.getPrdOriginalPrice()));
			itemInfo.setProductPrice(Utils.zeroIfNull(product.getPrdPrice()));
			itemInfo.setDiscount(product.getPrdDiscount());
			itemInfo.setRefundBillNo(product.getPrdRefundNo());
			itemInfo.setTariffType(Utils.zeroIfNull(product.getTariffType()));
			/*			itemInfo.setSalesType(SalesTypeStringEnum.forValue(product
								.getSalesType()));*/

			itemInfo.setSupportRtnWithoutReason(Utils.falseIfNull(product
					.getReturn7d()));
			itemInfo.setPremium(BigDecimal.ZERO);
			itemInfo.setPreSale(Utils.falseIfNull(product.getPrdPreSale()));
			itemInfo.setThirdPartyDiscount(Utils.zeroIfNull(product
					.getPrdDiscount3P()));
			itemInfo.setProductVer(product.getProductVersion());
			itemInfo.setPspProduct(product.isPspProduct());

			if (!CollectionUtils.isEmpty(refunds)) {
				for (Refund refund : refunds) {

					//找到商品上匹配退款单号且退款成功或申请中的退款单
					if (!StringUtils.isEmpty(itemInfo.getRefundBillNo())
							&& !StringUtils.isEmpty(refund.getRefundNo())
							&& itemInfo.getRefundBillNo().equals(
									refund.getRefundNo())
							&& refund.getRefundStatus() != null) {
						if (!refund.getRefundStatus().equals(-10)) {
							itemInfo.setRefundFreight(Utils.zeroIfNull(refund
									.getRefundAmountFreight()));
						}
						if (refund.getRefundStatus().equals(10)) {
							itemInfo.setRefundApproveFreight(Utils
									.zeroIfNull(refund.getRefundAmountFreight()));
						}
						break;
					}
				}
			}
			itemInfo.setPromotion(OrderInfoBuilder.convertFromProduct(product));

			itemInfo.setSubProductInfos(OrderHelper.buildSubProducts(order,
					product.getCataId()));

			orderItemInfos.add(itemInfo);
		}

		return orderItemInfos;
	}
}
